import { Component } from '@angular/core';

import { Events, NavController, AlertController, Platform, ModalController, App } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { SettingSealService } from './seal.service';
import { Config } from '../../../providers/config';

import { Common } from '../../../providers/common';

import _ from "lodash";
import {SettingIndexService} from "../index/index.service";


@Component({
	selector: 'page-setting-push',
	templateUrl: 'push.html',
  providers: [SettingIndexService]
})
export class SettingPushPage {
	moa_page_name: any = "page-setting-push";
  moa_page_explain: any = "设置新消息提醒";

  sealContent = "";

  userInfo: any = {};

  isPush = false;

  pushTypeList = [];

	constructor(
    public nav: NavController,
    public setttingIndexService: SettingIndexService,
    public alertCtrl: AlertController,
    public platform: Platform,
    public modalCtrl: ModalController,
    public common: Common,
    public events: Events,
    public appCtrl: App,
    public storage: Storage
	) {
    this.init();
	}

  init() {
    this.storage.get('userInfo').then(userInfo => {
      console.log("userInfo>>>>>>", userInfo);
      if (userInfo) {
        this.userInfo = userInfo;
        this.isPush = userInfo.isPush;
        if (userInfo.subPush) {
          this.pushTypeList = userInfo.subPush;
          console.log("pushTypeList>>>>>>>>>", this.pushTypeList);
        } else {
          this.storage.get("configs").then(configs => {
            let push_config = _.find(configs, {name: "push_config"});
            if (push_config) {
              this.userInfo.subPush = push_config["json"];
              this.pushTypeList = this.userInfo.subPush;
              this.storage.set("userInfo", this.userInfo);
            }
          });
        }
      }
    });
  }

  onChangeSubPushStatus($event, item) {
    let that = this;
    // 判断如果要请求的状态和服务器的状态一致，则不提交
    this.storage.get('userInfo').then(function (userInfo) {

      if (item) {
        _.forEach(that.pushTypeList, type => {
          if (type["pushType"] === item["pushType"]) {
            type["isPush"] = $event.checked;
          }
        });
      }

      that.storage.get('registrationId').then(function (registrationId) {
        console.log('----------------registrationId--------------');
        console.log(registrationId);
        that.setttingIndexService.changePushStatus(that.isPush, that.pushTypeList, registrationId).subscribe(data => {
          if (data) {
            that.userInfo.subPush = that.pushTypeList;
            that.storage.set('userInfo', that.userInfo);
          } else {
            that.isPush = !$event.checked;
            $event.checked = that.isPush;
          }
        });
      });
    });
  }

}
